#Proyecto 2 Introduccion a los Sistemas Embebidos
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import pygst
pygst.require('0.10')
gobject.threads_init()
import gst
import time
import random
from Tkinter import * 
from PIL import Image, ImageTk

def get_cards():
    return [i%8 for i in range(16)]#arreglo de 16, numeros del 0-7
def init_exposed():
    return [False for i in range(16)]

class DemoApp(Frame):
    """GStreamer/PocketSphinx Demo Application"""
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        """Initialize a DemoApp object"""
        #self.init_gui()
        #self.init_gst()  
        #vader = self.pipeline.get_by_name('vad')
        #vader.set_property('silent', True)      
        global cards,exposed,moves, card1,card2,state,B1,B2
        cards=get_cards()
        random.shuffle(cards)
        moves=0
        self.card1 = -1
        self.card2 = -1
        self.global_state = 0
        self.playing = False
        
        
        #self.buttons = [0][0]
        #self.photo = [0]
        #self.heroPhoto = [0]

    def init_gui(self):
        """Initialize the GUI components"""
##        self.window = gtk.Window()
##        self.window.connect("delete-event", gtk.main_quit)
##        self.window.set_default_size(600,400)
##        self.window.set_title("DotAMemory")
##        self.window.set_border_width(10)
##        vbox = gtk.VBox()
##        self.textbuf = gtk.TextBuffer()
##        self.text = gtk.TextView(self.textbuf)
##        self.text.set_wrap_mode(gtk.WRAP_WORD)
##        vbox.pack_start(self.text)
##        self.speak_button = gtk.ToggleButton("Hablar")
##        self.speak_button.connect('clicked', self.speak_clicked)
##
##        self.accept_button = gtk.ToggleButton("Aceptar")
##        self.accept_button.connect('clicked', self.accept_clicked)
##        self.cancel_button = gtk.ToggleButton("Borrar")
##        self.cancel_button.connect('clicked', self.cancel_clicked)
##
##        vbox.pack_start(self.speak_button, False, False, 5)
##        vbox.pack_start(self.accept_button, False, False, 6)
##        vbox.pack_start(self.cancel_button, False, False, 7)
##        self.window.add(vbox)
##        self.window.show_all()
                
        self.IconImages = [Image.open("/home/cristian/images/dota.jpg"),
                          Image.open("/home/cristian/images/aegis.jpg")]
        self.HeroImages = [Image.open("/home/cristian/images/"+str(i)+".jpg") for i in range(8)]
        
        size = 4            
        self.photo = [ImageTk.PhotoImage(self.IconImages[0]),ImageTk.PhotoImage(self.IconImages[1])]
        self.heroPhoto = [ImageTk.PhotoImage(self.HeroImages[i]) for i in range(8)]
        
        
        self.buttons = [[Button(self) for i in range(size)]for j in range(size)]
        for i in range(size):
            for j in range(size):
                self.buttons[i][j].grid(row=i, column=j)
                self.buttons[i][j]["image"] = self.photo[0]
                self.buttons[i][j]["command"] = eval("self.button"+str(i+j+(size-1)*i)+"_clicked")
                self.buttons[i][j]["bg"] = "black"
        self.QUIT = Button(self)
        self.QUIT["text"] = "QUIT"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit

        self.QUIT.grid(row=7, column=1)

        self.hi_there = Button(self)
        self.hi_there["text"] = "Hello",
        self.hi_there["command"] = self.say_hi
        self.hi_there.grid(row=7, column=2)
        self.entry = Entry(self, width = 25)
        self.entry.grid(row=8, column=1, columnspan = 2)
        
        self.playing = True
##        self.pipeline.set_state(gst.STATE_PLAYING)
##        
##        vader = self.pipeline.get_by_name('vad')
##        vader.set_property('silent', True)
##        self.window.destroy()
        
        #root.mainloop()
        #self.window.destroy()
        #self.listen_word()
        #root.destroy()

    def init_gst(self):
        """Initialize the speech components"""
        self.pipeline = gst.parse_launch('gconfaudiosrc ! audioconvert ! audioresample '
                                         + '! vader name=vad auto-threshold=true '
                                         + '! pocketsphinx name=asr ! fakesink')
        asr = self.pipeline.get_by_name('asr')
##        asr.connect('partial_result', self.asr_partial_result)
        asr.connect('result', self.asr_result)
        
        asr.set_property('configured', True)
        asr.set_property('lm', '/home/cristian/Escritorio/Sphinx/sphinx/python/LanguageModel/instrucciones.lm')
        asr.set_property('dict', '/home/cristian/Escritorio/Sphinx/sphinx/python/LanguageModel/instrucciones.dic')

        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect('message::application', self.application_message)

        self.pipeline.set_state(gst.STATE_PAUSED)

##    def asr_partial_result(self, asr, text, uttid):
##        """Forward partial result signals on the bus to the main thread."""
##        struct = gst.Structure('partial_result')
##        struct.set_value('hyp', text)
##        struct.set_value('uttid', uttid)
##        asr.post_message(gst.message_new_application(asr, struct))

    def asr_result(self, asr, text, uttid):
        """Forward result signals on the bus to the main thread."""
        struct = gst.Structure('result')
        struct.set_value('hyp', text)
        struct.set_value('uttid', uttid)
        asr.post_message(gst.message_new_application(asr, struct))
        

    def application_message(self, bus, msg):
        """Receive application messages from the bus."""
        msgtype = msg.structure.get_name()
##        if msgtype == 'partial_result':
##            self.partial_result(msg.structure['hyp'], msg.structure['uttid'])
        if msgtype == 'result':
            self.final_result(msg.structure['hyp'], msg.structure['uttid'])
            self.pipeline.set_state(gst.STATE_PAUSED)
            #self.speak_button.set_active(False)

##    def partial_result(self, hyp, uttid):
##        """Delete any previous selection, insert text and select it."""
##        # All this stuff appears as one single action
##        self.textbuf.begin_user_action()
##        self.textbuf.delete_selection(True, self.text.get_editable())
##        self.textbuf.insert_at_cursor(hyp)
##        ins = self.textbuf.get_insert()
##        iter = self.textbuf.get_iter_at_mark(ins)
##        iter.backward_chars(len(hyp))
##        self.textbuf.move_mark(ins, iter)
##        self.textbuf.end_user_action()

    def final_result(self, hyp, uttid):
        """Insert the final result."""
        #if self.playing:
        test = hyp
        if test == "UP":
            print "UP!"
            #self.accept_button.set_active(True)    
            #self.buttons[0][0].invoke()
        if test == "DOWN":
            print "DOWN!"
        if test == "LEFT":
            print "LEFT!"
        if test == "RIGHT":
            print "RIGHT!"
        if test == "PICK":
            print "PICK!"
        self.entry.delete(0, END)
        self.entry.insert(0, hyp)
##        else:
##            # All this stuff appears as one single action
##            self.textbuf.begin_user_action()
##            self.textbuf.delete_selection(True, self.text.get_editable())
##            self.textbuf.insert_at_cursor(hyp)
##            self.textbuf.end_user_action()
        
        #self.buttons[0][0]["bg"] = "green"

        ###################
        ## Termina Sphinx #
        ###################
        
    def listen_word(self,hyp,uttid):
        #self.pipeline.set_state(gst.STATE_PLAYING)
        self.buttons[0][0]["bg"] = "green"
        test = hyp
        if test == "UP":
            print "UP!"
            #self.buttons[0][0].invoke()
            


    # Funcion del boton speak 
    def speak_clicked(self, speak_button):
        """Handle button presses."""
        if speak_button.get_active():
            speak_button.set_label("Parar")
            self.pipeline.set_state(gst.STATE_PLAYING)
##        else:
##            speak_button.set_label("Hablar")
##            vader = self.pipeline.get_by_name('vad')
##            vader.set_property('silent', True)
    
##    # Funcion del boton Aceptar 
##    def accept_clicked(self, accept_button):
##        """Handle button presses."""
##        if accept_button.get_active():
##            #self.window.hide()
##            #self.window.set_visible(False)
##            
##            root = Tk()
##            root["bg"] = "black"
##                                  
##            def createWidgets(root):
##            size = 4            
##            self.photo = [ImageTk.PhotoImage(self.IconImages[0]),ImageTk.PhotoImage(self.IconImages[1])]
##            self.heroPhoto = [ImageTk.PhotoImage(self.HeroImages[i]) for i in range(8)]
##            
##            
##            self.buttons = [[Button(root) for i in range(size)]for j in range(size)]
##            for i in range(size):
##                for j in range(size):
##                    self.buttons[i][j].grid(row=i, column=j)
##                    self.buttons[i][j]["image"] = self.photo[0]
##                    self.buttons[i][j]["command"] = eval("self.button"+str(i+j+(size-1)*i)+"_clicked")
##                    self.buttons[i][j]["bg"] = "black"
##            self.QUIT = Button(root)
##            self.QUIT["text"] = "QUIT"
##            self.QUIT["fg"]   = "red"
##            self.QUIT["command"] =  root.quit
##
##            self.QUIT.grid(row=7, column=1)
##
##            self.hi_there = Button(root)
##            self.hi_there["text"] = "Hello",
##            self.hi_there["command"] = self.say_hi
##            self.hi_there.grid(row=7, column=2)
##            self.entry = Entry(root, width = 25)
##            self.entry.grid(row=8, column=1, columnspan = 2)
##            
##            self.playing = True
##            self.pipeline.set_state(gst.STATE_PLAYING)
##            self.window.destroy()
##            root.mainloop()
##            #self.window.destroy()
##            #self.listen_word()
##            root.destroy()
    
    def set_state(self,button,card):
        if self.global_state == 1:
            if button != self.B1:
                self.global_state = 0
                self.B2 = button
                self.card2 = card
                if self.check_pair():
                    self.B1["state"] = DISABLED
                    self.B2["state"] = DISABLED
                elif self.check_pair() == False:
                    self.B1["image"] = self.photo[0]
                    self.B2["image"] = self.photo[0]
                    self.card2 = -1
                    self.card2 = -1
            else:
                self.global_state = 1

        elif self.global_state == 0:
            self.B1 = button
            self.card1 = card
            self.global_state = self.global_state + 1

    def check_pair(self):
        if self.card1 == self.card2:
            return True
        else:
            return False

    def say_hi(self):
        """Handle button presses."""
        self.pipeline.set_state(gst.STATE_PLAYING)
    
    def button0_clicked(self):
        self.buttons[0][0]["image"] = self.heroPhoto[cards[0]]
        self.set_state(self.buttons[0][0],cards[0])

    def button1_clicked(self):
        self.buttons[0][1]["image"] = self.heroPhoto[cards[1]]
        self.set_state(self.buttons[0][1],cards[1])

    def button2_clicked(self):
        self.buttons[0][2]["image"] = self.heroPhoto[cards[2]]
        self.set_state(self.buttons[0][2],cards[2])

    def button3_clicked(self):
        self.buttons[0][3]["image"] = self.heroPhoto[cards[3]]
        self.set_state(self.buttons[0][3],cards[3])

    def button4_clicked(self):
        self.buttons[1][0]["image"] = self.heroPhoto[cards[4]]
        self.set_state(self.buttons[1][0],cards[4])

    def button5_clicked(self):
        self.buttons[1][1]["image"] = self.heroPhoto[cards[5]]
        self.set_state(self.buttons[1][1],cards[5])

    def button6_clicked(self):
        self.buttons[1][2]["image"] = self.heroPhoto[cards[6]]
        self.set_state(self.buttons[1][2],cards[6])

    def button7_clicked(self):
        self.buttons[1][3]["image"] = self.heroPhoto[cards[7]]
        self.set_state(self.buttons[1][3],cards[7])

    def button8_clicked(self):
        self.buttons[2][0]["image"] = self.heroPhoto[cards[8]]
        self.set_state(self.buttons[2][0],cards[8])

    def button9_clicked(self):
        self.buttons[2][1]["image"] = self.heroPhoto[cards[9]]
        self.set_state(self.buttons[2][1],cards[9])

    def button10_clicked(self):
        self.buttons[2][2]["image"] = self.heroPhoto[cards[10]]
        self.set_state(self.buttons[2][2],cards[10])

    def button11_clicked(self):
        self.buttons[2][3]["image"] = self.heroPhoto[cards[11]]
        self.set_state(self.buttons[2][3],cards[11])

    def button12_clicked(self):
        self.buttons[3][0]["image"] = self.heroPhoto[cards[12]]
        self.set_state(self.buttons[3][0],cards[12])
        
    def button13_clicked(self):
        self.buttons[3][1]["image"] = self.heroPhoto[cards[13]]
        self.set_state(self.buttons[3][1],cards[13])

    def button14_clicked(self):
        self.buttons[3][2]["image"] = self.heroPhoto[cards[14]]
        self.set_state(self.buttons[3][2],cards[14])

    def button15_clicked(self):
        self.buttons[3][3]["image"] = self.heroPhoto[cards[15]]
        self.set_state(self.buttons[3][3],cards[15])
    
    def cancel_clicked(self, cancel_button):
        """Handle button presses."""
        if cancel_button.get_active():
            self.textbuf.set_text("")

    def getText(self):
        start, end = self.textbuf.get_start_iter(), self.textbuf.get_end_iter()
        text = self.textbuf.get_text(start, end)
        return text


root = Tk()
app = DemoApp(master=root)
app.mainloop()
root.destroy()
#app = DemoApp()
#gtk.main()
